#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
    {
        {
            vector<int> indegree(numCourses, 0);
            vector<int> pre[numCourses];
            for (auto &e : prerequisites)
            {
                // 学0需要1 [0,1]
                pre[e[1]].push_back(e[0]);
                indegree[e[0]]++;

                // 1->0
            }
            vector<int> ret;

            queue<int> q;
            int count = 0;
            for (int i = 0; i < numCourses; i++)
            {
                if (indegree[i] == 0)
                    q.push(i);
            }
            while (!q.empty())
            {
                int cur = q.front();
                ret.push_back(cur);
                q.pop();
                count++;
                for (auto &e : pre[cur])
                {
                    indegree[e]--;
                    if (indegree[e] == 0)
                        q.push(e);
                }
            }
            if (count == numCourses)
            {
                return ret;
            }
            return {};
        }
    }
};